package cn.action.news;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import cn.action.BaseAction;
import cn.beans.News;
import cn.beans.NewsCategory;
import cn.beans.NewsFile;
import cn.busiBean.NewsBean;
import cn.constant.NewsConstant;
import cn.utils.PageModel;

import com.opensymphony.xwork2.ActionContext;

@SuppressWarnings("unchecked")
public class NewsAction extends BaseAction {

	private News news;
	private String newsId;
	private String ncId;
	private String errorinfo;
	private List listNews;
	private NewsCategory nc;
	private int currentPage=1;
	private int pageSize=15;
	private PageModel pm = new PageModel();
	private String keywords;
	private File pic;
	private String picFileName;
	private String picContentType;
	private String fileId;
	private NewsFile newsFile;
	private String title;
	private String isRecommended;
	
	private List<News> listNew = new ArrayList();
	/**
	 * 新增新闻公告
	 * @throws Exception
	 */
	public String addNews() throws Exception{
		String sadminId = (String)ActionContext.getContext().getSession().get("adminId");
		String sadminName = (String)ActionContext.getContext().getSession().get("adminName");
		if(null == sadminId){
			errorinfo = "Time over";
			return LOGIN;
		}else{
			nc = commonservice.findById(ncId, new NewsCategory());
			news.setCreAdminId(sadminId);
			news.setCreAdminName(sadminName);
			news.setCreDate(new Date());
			news.setLastEditorId(sadminId);
			news.setLastEditorName(sadminName);
			news.setLastEditTime(news.getCreDate());
			news.setCategory(nc);
			
			if(null != pic){
				InputStream is = new FileInputStream(pic);
				int pos = picFileName.lastIndexOf(".");
				String extName = picFileName.substring(pos).toLowerCase();
				if(!(".jpg".equals(extName) || ".gif".equals(extName) 
					|| ".jpeg".equals(extName) || ".png".equals(extName))){
					
					errorinfo = "picType";
					return INPUT;
				}else{
					commonservice.saveDemo(news);
					
					String uploadFilename = news.getId() + extName;
					String root = ServletActionContext.getServletContext()
							.getRealPath("/upload/news");
					File app = new File(root);
					if (!app.exists()) {
						app.mkdir();
					}
					File dest = new File(root, uploadFilename);

					OutputStream os;
					os = new FileOutputStream(dest);
					byte[] buffer = new byte[1024];
					int len = 0;
					int total = 0;
					while ((len = is.read(buffer)) > 0) {
						total += len;
						os.write(buffer, 0, len);
					}
					is.close();
					os.close();
					
					NewsFile nf = new NewsFile();
					nf.setAdminId(sadminId);
					nf.setAdminName(sadminName);
					nf.setCreDate(new Date());
					nf.setExtent(extName);
					nf.setName(picFileName);
					nf.setSaveName(uploadFilename);
					nf.setSize(total);
					nf.setNewsId(news.getId());
					
					commonservice.saveDemo(nf);
					
				}
			}else{
				commonservice.saveDemo(news);
			}
			return SUCCESS;
		}
	}
	
	/**
	 * 读新闻
	 * @return
	 */
	public String readNews(){
		if(null != newsId){
			news = commonservice.findById(newsId, new News());
			if(null != news){
				news.setReadTimes(news.getReadTimes() + 1);
				commonservice.updateDemo(news);
				
				nc = news.getCategory();
				String hql = "FROM NewsFile nf WHERE nf.newsId = ?";
				Object[] param = { news.getId() };
				List list = findSomeByHQL.findDataByHql(hql, param);
				if(null != list && list.size() > 0){
					newsFile = (NewsFile)list.get(0);
				}
				
			}
			
		}
		return SUCCESS;
	}
	
	/**
	 * 保存新闻修改
	 * @throws Exception
	 */
	public String updateNews() throws Exception{
		try{
			String sadminId = (String)ActionContext.getContext().getSession().get("adminId");
			String sadminName = (String)ActionContext.getContext().getSession().get("adminName");
			if(null == sadminId){
				errorinfo = "Time Over";
				return LOGIN;
			}else{
				nc = commonservice.findById(ncId, new NewsCategory());
				News ns = commonservice.findById(newsId, new News());
				ns.setTitle(news.getTitle());
				ns.setCategory(nc);
				ns.setContent(news.getContent());
				ns.setIsRecommended(news.getIsRecommended());
				ns.setLastEditorId(sadminId);
				ns.setLastEditorName(sadminName);
				ns.setLastEditTime(new Date());
				ns.setReadTimes(news.getReadTimes());
				ns.setAbstracts(news.getAbstracts());
				
				if(null != pic){
					InputStream is = new FileInputStream(pic);
					int pos = picFileName.lastIndexOf(".");
					String extName = picFileName.substring(pos).toLowerCase();
					if(!(".jpg".equals(extName) || ".gif".equals(extName) 
						|| ".jpeg".equals(extName) || ".png".equals(extName))){
						
						errorinfo = "picType";
						return "INPUT";
					}else{
						commonservice.updateDemo(ns);
						
						String uploadFilename = ns.getId() + extName;
						String root = ServletActionContext.getServletContext()
								.getRealPath("/upload/news");
						File app = new File(root);
						if (!app.exists()) {
							app.mkdir();
						}
						File dest = new File(root, uploadFilename);

						OutputStream os;
						os = new FileOutputStream(dest);
						byte[] buffer = new byte[1024];
						int len = 0;
						int total = 0;
						while ((len = is.read(buffer)) > 0) {
							total += len;
							os.write(buffer, 0, len);
						}
						is.close();
						os.close();
						
						String hql = "FROM NewsFile AS nf WHERE nf.newsId = ?";
						Object[] param = { ns.getId() };
						List list = findSomeByHQL.findDataByHql(hql, param);
						if(null != list && list.size() > 0){
							NewsFile nf = (NewsFile)list.get(0);
							nf.setAdminId(sadminId);
							nf.setAdminName(sadminName);
							nf.setCreDate(new Date());
							nf.setExtent(extName);
							nf.setName(picFileName);
							nf.setSaveName(uploadFilename);
							nf.setSize(total);
							
							commonservice.updateDemo(nf);
						}else{
							NewsFile nf = new NewsFile();
							nf.setAdminId(sadminId);
							nf.setAdminName(sadminName);
							nf.setCreDate(new Date());
							nf.setExtent(extName);
							nf.setName(picFileName);
							nf.setSaveName(uploadFilename);
							nf.setSize(total);
							nf.setNewsId(ns.getId());
							
							commonservice.saveDemo(nf);
						}
						
					}
				}else{
					commonservice.updateDemo(ns);
				}
				
				return SUCCESS;
			}
		}catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	
	/**
	 * 获取新闻列表
	 * @return
	 */
	public String getNewsList(){
		
		if(null == ncId || "".equals(ncId) || "null".equals(ncId)){
			ncId = "root";
		}
		
		pm.setCurrentPage(currentPage);
		pm.setPageSize(pageSize);

		List listOne = new ArrayList();
		String[] propertyName = { "category.id", "category.path" };
		String[] propertyCon = { "=", "like" };
		Object[] propertyValue = { ncId, ncId };
		String[] condition = { "OR" };
		listOne.add(propertyName);
		listOne.add(propertyCon);
		listOne.add(propertyValue);
		listOne.add(condition);
		
		List listTwo = new ArrayList();
		String[] propertyNameQuery = { "title","content","isRecommended" };
		String[] propertyConQuery = { "like","like","=" };
		Object[] propertyValueQuery = { keywords,keywords,isRecommended };
		String[] conditionQuery = { "OR","and"};
		listTwo.add(propertyNameQuery);
		listTwo.add(propertyConQuery);
		listTwo.add(propertyValueQuery);
		listTwo.add(conditionQuery);

		String[] orderPropertyName = { "creDate"};
		String[] orderValue = { "DESC"};

		pm = commonservice.findDataByPage(pm, "News", listOne, "AND", listTwo, null, null, null, null, orderPropertyName, orderValue);

		return SUCCESS;
		
	}
	
	/**
	 * 首页显示的新闻列表
	 * @return
	 */
	public void getNewsIndex() throws Exception{
		try{
			String hql = "FROM News AS n WHERE n.category.id != 'job' AND n.category.id != 'faqs' ORDER BY n.isRecommended DESC,n.lastEditTime DESC";
			List list = findSomeByHQL.findDataByHql(hql);
			int size = list.size() > NewsConstant.NUM_OF_INDEX?NewsConstant.NUM_OF_INDEX:list.size();
			if(size > 0){
				listNews = new ArrayList<NewsBean>();
				for(int i=0; i<size; i++){
					News n = (News)list.get(i);
					NewsBean nb = new NewsBean();
					nb.setId(n.getId());
					nb.setTitle(n.getTitle());
					listNews.add(nb);
				}
			}
			String jsonResult = this.changeListToStr(listNews);
			this.sendMsgAjax(jsonResult, null);
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 删除新闻
	 * @throws Exception
	 */
	public void deleteNews() throws Exception{
		try{
			String sadminId = (String)ActionContext.getContext().getSession().get("adminId");
			if(null == sadminId){
				this.sendMsgAjax("login", null);
			}else{
				System.out.println(newsId);
				String[] ids = newsId.split(",");
				int length = ids.length;
				for(int i=0; i<length; i++){
					News n = commonservice.findById(ids[i], new News());
					if(null != n){
						String hql = "FROM NewsFile nf WHERE nf.newsId = ?";
						Object[] param = { n.getId() };
						List list = findSomeByHQL.findDataByHql(hql, param);
						if(null != list && list.size() > 0){
							NewsFile nf = (NewsFile)list.get(0);
							String newsPath = ServletActionContext.getServletContext().getRealPath("/upload/news");
							String file = newsPath + "\\" + nf.getSaveName();
							File f = new File(file);
							if(f.exists()){
								f.delete();
							}
							commonservice.deleteDemo(nf, null);
						}
						
						commonservice.deleteDemo(n, null);
					}
				}
				
				this.sendMsgAjax("success", null);
			}
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 获取首页图片地址
	 * @throws Exception
	 */
	public void getPicUrls() throws Exception{
		try{
			String url = "/upload/news/";
			String hql = "FROM News AS n,NewsFile AS nf WHERE n.id = nf.newsId AND n.isRecommended = '1' ORDER BY n.lastEditTime DESC";
			List list = findSomeByHQL.findDataByHql(hql);
			String result = "[";
			
			if(null != list){
				int size = list.size();
				int num = 1;
				for(int i=0; i<size; i++){
					Object[] obj = (Object[])list.get(i);
					News n = (News)obj[0];
					NewsFile nf = (NewsFile)obj[1];
					if(null != n && null != nf){
						String picUrl = url + nf.getSaveName();
						
						result += "{'title':'";
						result += n.getTitle();
						result += "','picUrl':'";
						result += picUrl;
						result += "','newsId':'";
						result += n.getId();
						result += "'}";
						
						if(NewsConstant.PIC_OF_INDEX == num || i == size - 1){
							break;
						}else{
							result += ",";
							num ++;
						}
						
					}
				}
				result += "]";
				
				this.sendMsgAjax(result, null);
			}
			
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 修改新闻时,删除新闻热点图片
	 * @throws Exception
	 */
	public void deleteNewsFile() throws Exception{
		try{
			String sadminId = (String)ActionContext.getContext().getSession().get("adminId");
			if(null == sadminId){
				this.sendMsgAjax("login", null);
			}else{
				NewsFile nf = commonservice.findById(fileId, new NewsFile());
				String newsPath = ServletActionContext.getServletContext().getRealPath("/upload/news");
				String file = newsPath + "\\" + nf.getSaveName();
				File f = new File(file);
				if(f.exists()){
					f.delete();
				}
				commonservice.deleteDemo(nf, null);
				
				this.sendMsgAjax("success", null);
			}
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 前台新闻显示
	 * @return
	 */
	public void getProsceniumNewList()throws Exception
	{
		
		List listTwo = new ArrayList();
		String[] propertyNameQuery = { "isRecommended" };
		String[] propertyConQuery = { "=" };
		Object[] propertyValueQuery = { 1 };
		String[] conditionQuery =null ;
		listTwo.add(propertyNameQuery);
		listTwo.add(propertyConQuery);
		listTwo.add(propertyValueQuery);
		listTwo.add(conditionQuery);

		String[] orderPropertyName = {"readTimes","isRecommended","lastEditTime"};
		String[] orderValue = {"DESC","DESC", "DESC" };

		pm = commonservice.findDataByPage(pm, "News", null, null, listTwo, null, null, null, null, orderPropertyName, orderValue);
		
		if(pm != null && pm.getList() != null && !pm.getList().isEmpty()){
			List<News> list = pm.getList();
			int j = 0;
			for(int i =0;i<list.size();i++)
			{
				listNew.add(list.get(i));
				j++;
				if(j == 9){
					break;
				}
			}
		}
		
	}
	
	public String showNew(){
		List listTwo = new ArrayList();
		String[] propertyNameQuery = { "title","category.id"};
		String[] propertyConQuery = { "like","="};
		Object[] propertyValueQuery = { title,ncId };
		String[] conditionQuery ={ "and" } ;
		listTwo.add(propertyNameQuery);
		listTwo.add(propertyConQuery);
		listTwo.add(propertyValueQuery);
		listTwo.add(conditionQuery);

		String[] orderPropertyName = {"creDate","readTimes"};
		String[] orderValue = {"DESC","DESC"};
		
		pm=new PageModel();
		pm.setCurrentPage(currentPage);
		pm.setPageSize(pageSize);

		pm = commonservice.findDataByPage(pm, "News", null, null, listTwo, null, null, null, null, orderPropertyName, orderValue);
		
		if(pm != null && pm.getList() != null && !pm.getList().isEmpty()){
			int totalPage=0;
			if(pm.getTotalCount()%pm.getPageSize()==0){
				totalPage=pm.getTotalCount()/pm.getPageSize();
			}else{
				totalPage=pm.getTotalCount()/pm.getPageSize()+1;
			}
			pm.setTotalPage(totalPage);
		}
		PageModel model=new PageModel();
		model.setPageSize(10);
		model.setCurrentPage(1);
		String hql="from News o order by o.readTimes desc";
		model=commonservice.findByPage(hql, model);
		listNew=model.getList();
		
		return SUCCESS;
	}
	
	public String detail(){
		news=commonservice.findById(ncId, new News());
		news.setReadTimes(news.getReadTimes()+1);
		commonservice.saveDemo(news);
		PageModel model=new PageModel();
		model.setPageSize(10);
		model.setCurrentPage(1);
		String hql="from News o order by o.readTimes desc";
		model=commonservice.findByPage(hql, model);
		listNew=model.getList();
		
		return SUCCESS;
	}

	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}

	public String getNewsId() {
		return newsId;
	}

	public void setNewsId(String newsId) {
		this.newsId = newsId;
	}

	public String getNcId() {
		return ncId;
	}

	public void setNcId(String ncId) {
		this.ncId = ncId;
	}

	public String getErrorinfo() {
		return errorinfo;
	}

	public void setErrorinfo(String errorinfo) {
		this.errorinfo = errorinfo;
	}

	public List getListNews() {
		return listNews;
	}

	public void setListNews(List listNews) {
		this.listNews = listNews;
	}

	public NewsCategory getNc() {
		return nc;
	}

	public void setNc(NewsCategory nc) {
		this.nc = nc;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public PageModel getPm() {
		return pm;
	}

	public void setPm(PageModel pm) {
		this.pm = pm;
	}

	public String getKeywords() {
		return keywords;
	}

	public void setKeywords(String keywords) {
		this.keywords = keywords;
	}

	public File getPic() {
		return pic;
	}

	public void setPic(File pic) {
		this.pic = pic;
	}

	public String getPicFileName() {
		return picFileName;
	}

	public void setPicFileName(String picFileName) {
		this.picFileName = picFileName;
	}

	public String getPicContentType() {
		return picContentType;
	}

	public void setPicContentType(String picContentType) {
		this.picContentType = picContentType;
	}

	public String getFileId() {
		return fileId;
	}

	public void setFileId(String fileId) {
		this.fileId = fileId;
	}

	public NewsFile getNewsFile() {
		return newsFile;
	}

	public void setNewsFile(NewsFile newsFile) {
		this.newsFile = newsFile;
	}

	public List<News> getListNew() {
		return listNew;
	}

	public void setListNew(List<News> listNew) {
		this.listNew = listNew;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getIsRecommended() {
		return isRecommended;
	}

	public void setIsRecommended(String isRecommended) {
		this.isRecommended = isRecommended;
	}
	
	
}
